﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Model;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Data;
using System.Globalization;

namespace University.Workshop.DataAccess
{
    public static class RatingDataAccess
    {
        private const string ConnectionString = "Data Source=.\\sqlexpress; Initial Catalog=LQSdataBase; Integrated Security=true";

        public static decimal GetProductRatingsAverage(long productId)
        {
            decimal avg=0;
            decimal sum=0;
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection(ConnectionString);
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "SELECT Rate FROM Ratings WHERE ProductID=@Id";
                command.Parameters.AddWithValue("Id", productId);

                SqlCommand getTotal = connection.CreateCommand();
                getTotal.CommandText = "SELECT Count(*) FROM Ratings WHERE ProductID=@Id";
                getTotal.Parameters.AddWithValue("Id", productId);

                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sum = sum + (decimal.Parse(reader["Rate"].ToString(),CultureInfo.CurrentCulture));
                }
                reader.Close();
                
                decimal total = decimal.Parse(getTotal.ExecuteScalar().ToString(),CultureInfo.CurrentCulture);
                
                if(total>0)
                avg = sum / total;
            }
            catch (SqlException ex)
            {
                throw new DataAccessException("Error getting average", ex);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return Math.Ceiling(avg);
        }

        public static Rating InsertRating(Rating rate)
        {
            if (rate != null)
            {
                SqlConnection connection = null;
                try
                {
                    connection = new SqlConnection(ConnectionString);
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = "INSERT INTO Ratings(ProductID,UserID,RatingDate,Rate) VALUES(@Product,@User,@ratingDate,@Rate)";
                    command.Parameters.AddWithValue("Product", rate.ProductId);
                    command.Parameters.AddWithValue("User", rate.UserId);
                    command.Parameters.AddWithValue("ratingDate", rate.Date);
                    command.Parameters.AddWithValue("Rate", rate.Rate);
                    //command.Parameters.AddWithValue("Comment", rate.Comment);
                    SqlCommand getID = connection.CreateCommand();
                    getID.CommandText = "SELECT @@Identity";

                    connection.Open();
                    int result = command.ExecuteNonQuery();
                    if (result <= 0)
                    {
                        throw new DataAccessException("Error inserting a rating");
                    }
                    rate.RatingId = Convert.ToInt64(getID.ExecuteScalar(),CultureInfo.CurrentCulture);
                }
                catch (SqlException ex)
                {
                    throw new DataAccessException("Error inserting a rating", ex);
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }

            return rate;
        }

        public static Rating InsertComment(Rating rate)
        {
            if (rate != null)
            {
                SqlConnection connection = null;
                try
                {
                    connection = new SqlConnection(ConnectionString);
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = "INSERT INTO Ratings(ProductID,UserID,RatingDate,Comment) VALUES(@Product,@User,@ratingDate,@Comment)";
                    command.Parameters.AddWithValue("Product", rate.ProductId);
                    command.Parameters.AddWithValue("User", rate.UserId);
                    command.Parameters.AddWithValue("ratingDate", rate.Date);
                    command.Parameters.AddWithValue("Comment", rate.Comment);
                    //command.Parameters.AddWithValue("Comment", rate.Comment);
                    SqlCommand getID = connection.CreateCommand();
                    getID.CommandText = "SELECT @@Identity";

                    connection.Open();
                    int result = command.ExecuteNonQuery();
                    if (result <= 0)
                    {
                        throw new DataAccessException("Error inserting a comment");
                    }
                    rate.RatingId = Convert.ToInt64(getID.ExecuteScalar(),CultureInfo.CurrentCulture);
                }
                catch (SqlException ex)
                {
                    throw new DataAccessException("Error inserting a comment", ex);
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }

            return rate;
        }

        public static bool UserAlreadyRated(Rating rate)
        {
            bool result=false;

            SqlConnection connection = null;
            if (rate != null)
            {
                try
                {
                    connection = new SqlConnection(ConnectionString);
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = "SELECT Rate FROM Ratings WHERE ProductID=@Id AND UserID=@User";
                    command.Parameters.AddWithValue("Id", rate.ProductId);
                    command.Parameters.AddWithValue("User", rate.UserId);
                    connection.Open();
                    int filas = 0;
                    if (command.ExecuteScalar() != null)
                        filas = int.Parse(command.ExecuteScalar().ToString(),CultureInfo.CurrentCulture);
                    result = filas > 0;

                }
                catch (SqlException ex)
                {
                    throw new DataAccessException("Error verifying user rated", ex);
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }
            return result;            
        }


        public static Rating InsertUserRating(Rating rate)
        {
            if (rate != null)
            {
                SqlConnection connection = null;
                try
                {
                    connection = new SqlConnection(ConnectionString);
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = "INSERT INTO SellerFeedback(SellerID,BuyerID,RatingDate,Rate,FeedBack) VALUES(@Seller,@User,@ratingDate,@Rate,@Comment)";
                    command.Parameters.AddWithValue("Seller", rate.ProductId);
                    command.Parameters.AddWithValue("User", rate.UserId);
                    command.Parameters.AddWithValue("ratingDate", rate.Date);
                    command.Parameters.AddWithValue("Rate", rate.Rate);
                    command.Parameters.AddWithValue("Comment", rate.Comment);
                    SqlCommand getID = connection.CreateCommand();
                    getID.CommandText = "SELECT @@Identity";

                    connection.Open();
                    int result = command.ExecuteNonQuery();
                    if (result <= 0)
                    {
                        throw new DataAccessException("Error saving feedback");
                    }
                    rate.RatingId = Convert.ToInt64(getID.ExecuteScalar(), CultureInfo.CurrentCulture);
                }
                catch (SqlException ex)
                {
                    throw new DataAccessException("Error saving feedback", ex);
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                    }
                }
            }

            return rate;
        }

        public static decimal GetUserRatingsSum(long userId)
        {
            decimal sum = 0;
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection(ConnectionString);
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "SELECT Rate FROM SellerFeedback WHERE SellerID=@Id";
                command.Parameters.AddWithValue("Id", userId);

                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sum = sum + (decimal.Parse(reader["Rate"].ToString(), CultureInfo.CurrentCulture));
                }
                reader.Close();                
            }
            catch (SqlException ex)
            {
                throw new DataAccessException("Error getting average", ex);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return sum;
        }

        public static string GetLastUserFeedback(long userId)
        {
            StringBuilder feedback = new StringBuilder();
            SqlConnection connection = null;
            int contador = 0;
            try
            {
                connection = new SqlConnection(ConnectionString);
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "SELECT RatingDate,FeedBack FROM SellerFeedback WHERE SellerID=@Id ORDER BY RatingDate DESC";
                command.Parameters.AddWithValue("Id", userId);

                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    if (contador == 1)
                        continue;
                    feedback.AppendLine(reader["RatingDate"].ToString() + " :");
                    feedback.AppendLine(reader["FeedBack"].ToString());
                    feedback.AppendLine("............................................");
                    contador++;
                }
                reader.Close();
            }
            catch (SqlException ex)
            {
                throw new DataAccessException("Error getting average", ex);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return feedback.ToString();
        }
    }
}
